<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"> -->





      <!-- <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:homepage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:homepage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:homepage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:homepage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="homepageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="首页id" align="center" prop="homepageId" /> -->


      <el-table-column label="公告/广播信息" align="center" prop="broadcastInformation" />
      <el-table-column label="文字介绍" align="center" prop="textIntro" />

      <el-table-column label="文字介绍英文" align="center" prop="textIntroEnglish" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="首页图片" align="center" prop="homeUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.homeUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="轮播图" align="center" prop="pictureUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.pictureUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:homepage:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:homepage:remove']"
          >删除</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleProductUpdate(scope.row)"
            v-hasPermi="['system:package:edit111']"
          >配置商品</el-button>
        </template>
      </el-table-column>
    </el-table>



    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--  配置商品 -->
    <el-dialog :title="title" :visible.sync="openProduct" width="800px" append-to-body>
      <div>
    <el-spinner v-if="loading" size="large" class="spinner"></el-spinner>
    <el-container v-else>
      <el-row>
        <el-col v-for="product in productList" :key="product.productId" :span="8">
          <el-card class="product-card" :body-style="{ padding: '20px' }">
            <el-checkbox
           v-model="selectedProductIds"
          :label="product.productId"

            @change="handleProductSelection(product)"
            class="product-checkbox"

            >
              <img :src="product.productPhoto" alt="Product Photo" class="product-image" />
              <div class="product-info">
                <h3>{{ product.productName }}</h3>
              </div>
            </el-checkbox>
          </el-card>
        </el-col>
      </el-row>
    </el-container>
  </div>

  <!-- 在 footer 插槽中放置按钮 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="openProduct = false">取消</el-button>
    <el-button type="primary" @click="saveSelectedProducts">保存</el-button>
  </span>
</el-dialog>


    <!-- 添加或修改小程序首页信息管理 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="公告" prop="broadcastInformation">
          <el-input v-model="form.broadcastInformation" placeholder="请输入公告/广播信息" />
        </el-form-item>
        <el-form-item label="文字介绍" prop="textIntro">
          <el-input v-model="form.textIntro" placeholder="请输入文字介绍" />
        </el-form-item>
        <el-form-item label="文字介绍英文" prop="textIntroEnglish">
          <el-input v-model="form.textIntroEnglish" placeholder="请输入文字介绍英文" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>


        <el-form-item label="首页图片" prop="homeUrl">
          <image-upload
            v-model="form.homeUrl"
            @before-upload="checkExistingImage"
          />
        </el-form-item>

        <el-form-item label="轮播图" prop="pictureUrl">
          <image-upload v-model="form.pictureUrl"/>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>



</template>

<script>
import { listHomepage, getHomepage, delHomepage, addHomepage, updateHomepage ,listProduct ,configureRecommenCommodities ,selectTbHomeRecommendsProductList } from "@/api/system/homepage";

export default {
  name: "Homepage",
  data() {
    return {
      //弹窗状态
      openProduct: false,


      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTbHomeRecommendsProduct: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小程序首页信息管理 表格数据
      homepageList: [],
      // 首页推荐商品表格数据
      tbHomeRecommendsProductList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tempalteId: null,
        recommendsProductId: null,
        merchantId: null,
        broadcastInformation: null,
        textIntro: null,
        pictureUrl: null
      },
      productList: [],  // 商品列表
      selectedProductIds: [],  // 选中的商品ID数组
          // 商品列表
          productList: [],
      selectedProducts: [], // 存储选中商品的数组
    openProduct: false,
    loading: false,
    saveProductList: [], // 假设从服务器获取商品列表
    checkedProducts: this.selectedProductIds,
     // 存储每个商品的数量
    productQuantities: [],
    packageId: 0,
    homepageId:0,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getProductList();
  },


  methods: {
 checkExistingImage(file) {
      if (this.form.homeUrl) {
        this.$message.warning('首页图片一张就够了');
        return false; // 阻止上传
      }
      return true; // 允许上传
    },
     getTbHomeRecommendsProductList(homepageId){
      this.loading = true;
      this.selectedProductIds = [];
      selectTbHomeRecommendsProductList(homepageId).then(response => {


        // 提取 productId 并放入 selectedProducts 数组
        this.selectedProductIds = response.rows.map(item => item.productId);


          this.total = response.total;
          this.loading = false;
      })
  },
    //点击商品选中
    handleProductSelection(product) {
  const productId = product.productId;


  console.log(this.selectedProductIds);
},
   //保存配置商品方法
    saveSelectedProducts() {
    // 检查是否选中了商品
    if (this.selectedProductIds.length === 0) {
      this.$message.warning('请至少选择一个商品');
      return;
    }

    // // // 打印调试信息
    // console.log('选中的商品 ID:', this.selectedProductIds);

    // 发送请求新增套餐管理
    const data = {
      homepageId: this.homepageId,
      selectedProducts: this.selectedProductIds,
    };

      console.log(data)

      configureRecommenCommodities(data).then(response => {
        // 处理请求成功的情况
        console.log('保存成功:', response.data);
        this.$message.success('保存成功');
        this.openProduct = false; // 关闭对话框
        this.getList(); // 刷新列表或其他需要的操作
      })
      .catch(error => {
        // 处理请求失败的情况
        console.error('保存失败:', error);
        this.$message.error('保存失败，请重试');
      })
      .finally(() => {
        this.loading = false; // 确保无论成功还是失败都停止加载状态
      });

},
    //查询商品
    getProductList() {
      this.loading = true;
      listProduct(this.queryProductParams)
        .then(response => {
          this.productList = response.rows; // 根据实际返回数据结构调整
          this.total = response.total;
          this.loading = false;

          console.log(this.productList);
        })
        .catch(error => {
          console.error('Failed to fetch products:', error);
          this.loading = false;
        });
    },

    /** 配置菜单按钮操作 */
    handleProductUpdate(row){
      this.openProduct = true;
      this.title = "推荐商品配置管理";
    this.homepageId = row.homepageId || this.ids

      //查找已配置商品
      this.getTbHomeRecommendsProductList(this.homepageId);
  },

    /** 查询小程序首页信息管理 列表 */
    getList() {
      this.loading = true;
      listHomepage(this.queryParams).then(response => {
        this.homepageList = response.rows;
        console.log(this.homepageList)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        homepageId: null,
        tempalteId: null,
        recommendsProductId: null,
        merchantId: null,
        broadcastInformation: null,
        textIntro: null,
        remark: null,
        pictureUrl: null
      };
      this.tbHomeRecommendsProductList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.homepageId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加小程序首页信息管理 ";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const homepageId = row.homepageId || this.ids
      getHomepage(homepageId).then(response => {
        this.form = response.data;
        this.tbHomeRecommendsProductList = response.data.tbHomeRecommendsProductList;
        this.open = true;
        this.title = "修改小程序首页信息管理 ";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.tbHomeRecommendsProductList = this.tbHomeRecommendsProductList;
          if (this.form.homepageId != null) {
            updateHomepage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHomepage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const homepageIds = row.homepageId || this.ids;
      this.$modal.confirm('是否确认删除小程序首页信息管理 编号为"' + homepageIds + '"的数据项？').then(function() {
        return delHomepage(homepageIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 首页推荐商品序号 */
    rowTbHomeRecommendsProductIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 首页推荐商品添加按钮操作 */
    handleAddTbHomeRecommendsProduct() {
      let obj = {};
      obj.productId = "";
      this.tbHomeRecommendsProductList.push(obj);
    },
    /** 首页推荐商品删除按钮操作 */
    handleDeleteTbHomeRecommendsProduct() {
      if (this.checkedTbHomeRecommendsProduct.length == 0) {
        this.$modal.msgError("请先选择要删除的首页推荐商品数据");
      } else {
        const tbHomeRecommendsProductList = this.tbHomeRecommendsProductList;
        const checkedTbHomeRecommendsProduct = this.checkedTbHomeRecommendsProduct;
        this.tbHomeRecommendsProductList = tbHomeRecommendsProductList.filter(function(item) {
          return checkedTbHomeRecommendsProduct.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleTbHomeRecommendsProductSelectionChange(selection) {
      this.checkedTbHomeRecommendsProduct = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/homepage/export', {
        ...this.queryParams
      }, `homepage_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.product-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.product-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.product-checkbox {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.product-quantity {
  margin-top: 10px;
}

.product-image {
  max-width: 80%;
  height: auto;
}

.product-info {
  text-align: center;
}
</style>
